﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;

namespace Common.Utility
{
    /// <summary>
    /// Excel读取类
    /// liuzhao
    /// 2012.4.13
    /// </summary>
    public static class ExcelReader
    {
        /// <summary>
        /// 获取Excel中所有的工作表名称
        /// </summary>
        /// <param name="fpath">Excel文件</param>
        /// <returns></returns>
        public static List<string> GetSheets(string fpath)
        {
            List<string> list = new List<string>();
            string connString = GetConnString(fpath);
            using (OleDbConnection conn = new OleDbConnection(connString))
            {
                try
                {
                    conn.Open();
                    DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                    foreach (DataRow row in table.Rows)
                    {
                        list.Add(row[2].ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }               
            }
            return list;
        }

        /// <summary>
        /// 读取Excel文件到DataTabel
        /// </summary>
        /// <param name="fpath">Excel文件绝对路径</param>
        /// <param name="sheet">工作簿名称</param>
        /// <param name="hdr">第一行是否为标题</param>
        /// <returns></returns>
        public static DataTable ReadExcel(string fpath, string sheet)
        {
            DataTable dt = new DataTable();
            string connString = GetConnString(fpath);
            OleDbDataAdapter ada = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheet), connString);
            ada.Fill(dt);
            return dt;
        }

        /// <summary>
        /// 根据Excel文件自动生成相应的链接字符串
        /// </summary>
        /// <param name="fpath"></param>
        /// <returns></returns>
        private static string GetConnString(string fpath)
        {
            string ext = Path.GetExtension(fpath).ToLower();
            string connString = null;
            if (ext.ToLower() == ".xls")
            {
                connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", fpath);
            }
            else
            {
                connString = string.Format("Provider=Microsoft.ace.oledb.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'", fpath);
            }

            return connString;
        }


    }
}
